package com.snpic.appaw.module.third.service.sms;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.snpic.appaw.module.third.config.SmsConfig;
import com.snpic.appaw.module.third.config.TSmsTemplateConfigInfo;
import com.snpic.appaw.module.third.controller.admin.sms.vo.SmsReqVO;
import com.snpic.appaw.module.third.controller.admin.sms.vo.SmsRespVO;
import com.snpic.appaw.module.third.dal.pojo.SmsReqEntity;
import com.snpic.appaw.module.third.service.common.ThirdPartyFlowRecordService;
import com.snpic.appaw.module.third.service.httpclient.HttpClientServerImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import static com.snpic.appaw.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.snpic.appaw.module.third.enums.ErrorCodeConstants.SMS_SEND_FAILED;
import static com.snpic.appaw.module.third.enums.ErrorCodeConstants.SMS_TEMPLATE_NOT_FOUND;

/**
 * @author JiJun
 * @date 2025/8/28 16:14
 * @修改时间 2025/8/28 16:14
 * @description
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SmsServiceImpl implements SmsService {

	private final SmsConfig smsConfig;
	private final RestTemplate restTemplate; // 需要添加RestTemplate配置
	private final TSmsTemplateConfigInfo smsTemplateConfigInfo;
	private final ThirdPartyFlowRecordService thirdPartyFlowRecordService;
	private final HttpClientServerImpl httpClientServer;
	/**
	 * 发送单条短信
	 */
	@Override

	public SmsRespVO sendSmsOne(SmsReqVO requestVO) {
		String smsTemplateKey = requestVO.getSmsTemplateKey();
		String businessType = requestVO.getBusinessType();
		String[] templateParams = requestVO.getTemplateParams();
		String phone = requestVO.getToMobile();
		// 获取短信模板内容
		String smsTemplateContent = smsTemplateConfigInfo.getTemplateByKey(smsTemplateKey);
		if (StrUtil.isBlank(smsTemplateContent)) {
			log.error("{}短信模板不存在，模板key：{}", businessType, smsTemplateKey);
			throw exception(SMS_TEMPLATE_NOT_FOUND);
		}
		//把短信模板和短信内容得prams拼接为完整短信
		String smsContent = String.format(smsTemplateContent, templateParams);


		SmsReqEntity smsRequest = smsConfig.createSmsRequest(phone, smsContent);
		    // 使用HttpClient服务发送请求

		String responseJson = null;
		try {
			responseJson = httpClientServer.doPostJson(
					smsConfig.getUrl(),
					smsRequest,
					new HashMap<String,String>(),
					"短信平台",
					businessType
			);
    } catch (HttpClientServerImpl.HttpClientException e) {
        log.error("短信接口调用失败", e);
        throw exception(SMS_SEND_FAILED);
    }
		SmsRespVO smsRespVO = JSONUtil.toBean(responseJson, SmsRespVO.class);
		return smsRespVO;

	}
}
